﻿//***************************************************************************
// Project:   MDT 2010 Wizard Editor
// File:      Variables.cs
// Purpose:   Form for displaying the variables passed into a wizard and the
//            values returned.
//
// Version:   2.0.0
//
// Change history:
// 2.0.0  mniehaus  10/11/2009  Created initial version.
//
//***************************************************************************

namespace WizardEditor
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Diagnostics;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;
    using System.Xml;
    using Microsoft.Win32;

    /// <summary>
    /// Form for displaying the variables passed into a wizard and the
    /// values returned.
    /// </summary>
    internal partial class Variables : Form
    {
        #region Instance variables

        String definitionFile;
        String definitionDirectory;

        #endregion Instance variables

        #region Constructor

        /// <summary>
        /// Constructor
        /// </summary>
        internal Variables()
        {
            InitializeComponent();
        }

        #endregion Constructor

        #region Internal properties

        /// <summary>
        /// Sets the full path of the definition file currently being edited.
        /// </summary>
        internal String DefinitionFile
        {
            set
            {
                definitionFile = value;
                definitionDirectory = Directory.GetParent(definitionFile).FullName;
            }
        }

        #endregion Internal properties

        #region Event handlers

        private void Variables_Load(object sender, EventArgs e)
        {
            String mdtDistributionDir;
            String filePath;

            // Clean up from previous execution
            if (Directory.Exists(@"C:\MININT"))
                Directory.Delete(@"C:\MININT", true);

            // Figure out the deployment share path
            if (File.Exists(Directory.GetParent(definitionDirectory).FullName + @"\Control\Version.xml"))
                mdtDistributionDir = Directory.GetParent(definitionDirectory).FullName;
            else
                mdtDistributionDir = String.Empty;

            // Run ZTIGather.wsf if it can be found
            filePath = Utility.FindFile(definitionDirectory, "ZTIGather.wsf");
            if (!String.IsNullOrEmpty(filePath))
            {
                String parameters = "\"" + filePath + "\" /localonly /DeploymentType:NEWCOMPUTER /DeploymentMethod:UNC";

                if (!String.IsNullOrEmpty(mdtDistributionDir))
                    parameters += " /DeployRoot:\"" + mdtDistributionDir + "\"";

                // Launch ZTIGather.wsf to get information about the current machine.  Have it shove in a few default
                // values too for DeploymentType, DeploymentMethod, and DeployRoot so that the wizard works better.
                Process gatherProcess = new Process();
                ProcessStartInfo startInfo = new ProcessStartInfo("cscript.exe", parameters);
                startInfo.WindowStyle = ProcessWindowStyle.Normal;
                startInfo.UseShellExecute = false;
                gatherProcess.StartInfo = startInfo;
                gatherProcess.Start();
                gatherProcess.WaitForExit();
            }

            // Load the variables
            LoadVariables();
        }

        private void buttonRun_Click(object sender, EventArgs e)
        {
            String filePath;

            // Save the modified VARIABLES.DAT
            XmlDocument variables = new XmlDocument();
            variables.LoadXml("<MediaVarList Version=\"4.00.5345.0000\" />");
            foreach (DataGridViewRow variableRow in variablesGrid.Rows)
            {
                if (variableRow.Cells[0].Value != null && variableRow.Cells[1].Value != null)
                {
                    XmlElement newVar = variables.CreateElement("var");
                    newVar.SetAttribute("name", variableRow.Cells[0].Value.ToString().ToUpper(CultureInfo.CurrentCulture));
                    newVar.AppendChild(variables.CreateCDataSection(variableRow.Cells[1].Value.ToString()));
                    variables.DocumentElement.AppendChild(newVar);
                }
            }
            variables.Save(@"C:\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT");

            // Now run Wizard.hta if it can be found
            filePath = Utility.FindFile(definitionDirectory, "Wizard.hta");
            if (String.IsNullOrEmpty(filePath))
            {
                MessageBox.Show("Unable to test wizard because the files required could not be found.", "Unable to test wizard",
                    MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
                return;
            }

            // Make sure the required files are present in the same directory
            foreach (String requiredFile in new String[] { 
                "Wizard.hta", "Wizard.css", "WizUtility.vbs", "ZTIUtility.vbs", "ZTIConfigFile.vbs", "ZTIDataAccess.vbs", "ZTIBCDUtility.vbs", "ZTINicUtility.vbs", 
                "Wizard.ico", "BackButton.JPG", "plusicon.gif", "minusico.gif", "SelectItem.jpg", "WelcomeBanner.jpg", "btnout.png", "btnover.png", "btnsel.png", "BackButton.png", "FolderIcon.png", "ItemIcon1.png", "MinusIcon1.png", "PlusIcon1.png", "SelectItem.png" })
            {
                if (!File.Exists(definitionDirectory + @"\" + requiredFile))
                {
                    filePath = Utility.FindFile(definitionDirectory, requiredFile);
                    if (!String.IsNullOrEmpty(filePath))
                        File.Copy(filePath, definitionDirectory + @"\" + requiredFile, true);
                }
            }

            // Launch Wizard
            Process wizProcess = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo("mshta.exe", "\"" + definitionDirectory + "\\Wizard.hta\" /definition:\"" + definitionFile + "\" /debug:true");
            startInfo.WindowStyle = ProcessWindowStyle.Normal;
            startInfo.UseShellExecute = false;
            wizProcess.StartInfo = startInfo;
            wizProcess.Start();
            wizProcess.WaitForExit();

            // Re-populate the variable list
            LoadVariables();

            // Clean up the MININT directory
            if (Directory.Exists(@"C:\MININT"))
                Directory.Delete(@"C:\MININT", true);

            // Switch the buttons and label
            buttonCancel.Enabled = false;
            buttonRun.Enabled = false;
            buttonClose.Visible = true;
            buttonClose.DialogResult = DialogResult.OK;
            labelVariables.Text = "Review the results of the wizard below.";
        }

        #endregion Event handlers

        #region Private methods

        private void LoadVariables()
        {
            // Load VARIABLES.DAT
            XmlDocument variables = new XmlDocument();
            if (File.Exists(@"C:\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT"))
            {
                variables.Load(@"C:\MININT\SMSOSD\OSDLOGS\VARIABLES.DAT");
            }
            else
            {
                variables.LoadXml("<MediaVarList Version=\"4.00.5345.0000\" />");
            }

            // Populate the data grid view
            variablesGrid.Rows.Clear();
            foreach (XmlNode variableNode in variables.DocumentElement)
            {
                variablesGrid.Rows.Add(variableNode.Attributes["name"].Value, variableNode.InnerText);
            }
        }

        #endregion Private methods
    }
}
